//
//  ClassSongConntroller.m
//  A段项目音乐播放
//
//  Created by 太阳 on 15/5/25.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//
#import "DataBaseHandler.h"
#import "ClassSongConntroller.h"
#import "SingerModel.h"
#import <AFNetworking/AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "ClassViewCell.h"
#import "playViewController.h"
#import "SingerState.h"
#import "myButton.h"
#import "MJRefresh.h"
#import "PendulumView.h"
#import "CollectDatabase.h"
//@protocol playWindowDelegate <NSObject>
//
//- (void)sendState;
//
//@end
@interface ClassSongConntroller ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation ClassSongConntroller

- (void)loadView
{
    [super loadView];
    
    UIColor *ballColor = [UIColor colorWithRed:0.47 green:0.60 blue:0.89 alpha:1];
    PendulumView *pendulum = [[PendulumView alloc] initWithFrame:self.view.bounds ballColor:ballColor];
    [self.view addSubview:pendulum];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self =[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    self.modelArray = [NSMutableArray array];
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self builtInterface];
    [self requestNet];
}
- (void)builtInterface
{
    self.mytableview = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain] autorelease];
    [self.mytableview setBackgroundColor:[UIColor whiteColor]];
    [self.mytableview.header beginRefreshing];
    [self.mytableview addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadgart)];
    [self.mytableview addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loctge)];
    self.mytableview.delegate = self;
    self.mytableview.dataSource = self;
    [self.view addSubview:self.mytableview];
    self.mytableview.separatorColor = [UIColor whiteColor];
    [self.mytableview registerClass:[ClassViewCell class] forCellReuseIdentifier:@"cell"];
    [self.mytableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellcell"];
    
//    [self.mytableview setBackgroundView:[self setBurlWithString:self.mymodel.pic_url_240_200]];
    
}

-(void)loadgart

{
    [self.modelArray removeAllObjects];
    [self.mytableview reloadData];
    [self requestNet];
    [self.mytableview.header endRefreshing];
    self.i =0;
    
}
-(void)loctge

{
    
    self.i=2;
    
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/channel/%@/songs?size=50&page=%d&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.mymodel.songlist_id,self.i];
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSData *data = [NSData dataWithData:responseObject];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"data"];
        //        self.modelArray = [NSMutableArray array];
        self.modelArray = [NSMutableArray array];
        for (NSDictionary *dicc in array) {
            SingerModel *model  = [[[SingerModel alloc]init] autorelease];
            [model setValuesForKeysWithDictionary:dicc];
            NSArray *arrray = [dicc objectForKey:@"auditionList"];
            NSInteger num = [arrray count];
            if (num != 0) {
                NSDictionary *diccc = [arrray objectAtIndex:num - 1];//标准音质
                [model setValuesForKeysWithDictionary:diccc];
                [self.modelArray addObject:model];
            }
            //            NSArray *arrrray = [dicc objectForKey:@"mvList"];
            //            NSDictionary *dicccc = [arrrray objectAtIndex:0];
            //            NSString *strrrr = [dicccc objectForKey:@"picUrl"];
            //            [model setValue:strrrr forKey:@"picUrl"];
        }
        
        [self.mytableview reloadData];
        self.mytableview.separatorColor = [UIColor colorWithWhite:0.2 alpha:0.5];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    
    [self.mytableview.footer endRefreshing];
    
    self.i++;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.modelArray count];
}

- (UIView *)setBurlWithString:(NSString *)str
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    UIImageView *imageview = [[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.height)] autorelease];
    
    NSURL *url = [NSURL URLWithString:str];
    CIImage *ciimage = [CIImage imageWithContentsOfURL:url];
    CIContext *context = [CIContext contextWithOptions:nil];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:ciimage forKey:kCIInputImageKey];
    [filter setValue:@6.0f forKey:@"inputRadius"];
    
    CIImage *outimage = [filter outputImage];
    
    CGImageRef cgimg = [context createCGImage:outimage fromRect:[outimage extent]];
    UIImage *image = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);
    imageview.image = image;
    [view addSubview:imageview];
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.modelArray.count == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellcell"];
//        cell.textLabel.text = @"没东西";
        return cell;
    } else {
        ClassViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    SingerModel *model = [self.modelArray objectAtIndex:indexPath.row];

    
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", model.picUrl]] placeholderImage:nil options:SDWebImageRetryFailed];
        cell.labelOfName.text = [NSString stringWithFormat:@"%@-%@", model.name, model.singerName];
        [cell setBackgroundColor:[UIColor whiteColor]];
        cell.labelOfAlbumName.text = model.albumName;
                cell.addButton.row = (NSInteger)indexPath.row;
                cell.addButton.section = (NSInteger)indexPath.section;
        [cell.addButton addTarget:self action:@selector(buttonaction:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.collectButton.row = indexPath.row;
        [cell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    return cell;
    }
//    return cell;
}

// 收藏按钮
- (void)collectButtonAction:(myButton *)sender
{
    self.myview = [[[UIView alloc]init] autorelease];
    [self.myview setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
    
    myButton *collectionButton = [myButton buttonWithType:UIButtonTypeSystem];
    collectionButton.layer.borderWidth = 1;
    collectionButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [collectionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [collectionButton setTitle:@"收藏" forState:UIControlStateNormal];
    collectionButton.row = sender.row;
    //    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.3 green:1 blue:1 alpha:1]];
    collectionButton.frame = CGRectMake(10, 30, [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
    [collectionButton addTarget:self action:@selector(collectionbuttonactions:) forControlEvents:UIControlEventTouchUpInside];
    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
    [self.myview addSubview:collectionButton];
    self.myview.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.myview.layer.borderWidth = 1;
    NSArray *array = [NSArray array];
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    int i = 0;
    for (NSString *str in array2) {
        myButton *button = [myButton buttonWithType:UIButtonTypeSystem];
        //        [button setBackgroundColor:[UIColor redColor]];
        [button setTitle:str forState:UIControlStateNormal];
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        button.layer.borderWidth = 1;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.row = sender.row;
        [button setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
        button.frame = CGRectMake(10, 75 + i * (30 + 20) , [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
        [button addTarget:self action:@selector(custonaction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        [self.myview addSubview:button];
        i++;
    }
    [self.view addSubview:self.myview];
    [self.myview setBackgroundColor:[UIColor whiteColor]];
    self.myview.frame = CGRectMake(50, 150, [UIScreen mainScreen].bounds.size.width - 100, 120 + i * 40);
    
}
//自定歌单
- (void)custonaction:(myButton *)sender
{
    SingerModel *model = [self.modelArray objectAtIndex:sender.row];
    DataBaseHandler *da = [DataBaseHandler shareInstance];
    
    
    NSArray *array = [NSArray array];
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    
    NSString *srt = [array2 objectAtIndex:sender.tag - 1];
    
    [da insertmodel:model str:srt];
    UIAlertView *al = [[[UIAlertView alloc] initWithTitle:@"添加成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [al show];
    [self.myview removeFromSuperview];
    
}

//收藏列表
- (void)collectionbuttonactions:(myButton *)inte
{
    SingerModel *model = [self.modelArray objectAtIndex:inte.row];
    [CollectDatabase insertWithModel:model];
    UIAlertView *alvi = [[[UIAlertView alloc]initWithTitle:@"收藏成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [alvi show];
    [self.myview removeFromSuperview];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}




- (void)buttonaction:(myButton *)sender
{
    myButton *button = (myButton *)sender;
    SingerModel *model = [self.modelArray objectAtIndex:button.row];
    SingerState *singer = [SingerState shareOfPlayState];
    singer.addNum ++;  //添加数量
    
    [singer.playListAddress insertObject:model atIndex:singer.num + singer.addNum];
    
    playViewController *play = [[[playViewController alloc]init] autorelease];
   
    [play.songListTableview insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:singer.num + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationMiddle];
    
    [play.songListTableview reloadData];
    NSLog(@"插入%@", model.name);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//请求网络
- (void)requestNet
{
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/channel/%@/songs?size=50&page=1&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.mymodel.songlist_id];
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSData *data = [NSData dataWithData:responseObject];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"data"];
//        self.modelArray = [NSMutableArray array];
    
        for (NSDictionary *dicc in array) {
            SingerModel *model  = [[[SingerModel alloc]init] autorelease];
            [model setValuesForKeysWithDictionary:dicc];
            NSArray *arrray = [dicc objectForKey:@"auditionList"];
            NSInteger num = [arrray count];
            if (num != 0) {
                NSDictionary *diccc = [arrray objectAtIndex:num - 1];//标准音质
                [model setValuesForKeysWithDictionary:diccc];
                [self.modelArray addObject:model];
            }
//            NSArray *arrrray = [dicc objectForKey:@"mvList"];
//            NSDictionary *dicccc = [arrrray objectAtIndex:0];
//            NSString *strrrr = [dicccc objectForKey:@"picUrl"];
//            [model setValue:strrrr forKey:@"picUrl"];
        }
        
        [self.mytableview reloadData];
        self.mytableview.separatorColor = [UIColor colorWithWhite:0.2 alpha:0.5];

        [self.view bringSubviewToFront:self.mytableview];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    playViewController *play = [playViewController shareStateOfViewcontroller];
    [play playWithModel:self.modelArray index:indexPath.row];
    
//    [play.songListTableview reloadData];
//    [self.navigationController pushViewController:play animated:YES];
    [self.navigationController presentViewController:play animated:YES completion:nil];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
